package com.me.web;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;

@WebServlet("/CheckCode")
public class CheckCode extends HttpServlet {
	private int width = 80;
	private int height = 20;
	private int fontHeight = 16;
	private int codeCount = 4;
	private final char[] codeSequence = new char[36];
	private int x = 16;
	private int codeY = 18;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException {
		for (int i = 0; i < 10; i++) {
			codeSequence[i] = (char) (i + 48);
		}
		for (int i = 0; i < 26; i++) {
			codeSequence[i + 10] = (char) ('A' + i);
		}

		//构造预自定义图像
		BufferedImage Img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

		//返回 Graphics2D
		Graphics g = Img.getGraphics();
		Random random = new Random();

		//填充图像为白色
		g.setColor(Color.WHITE);
		//填充指定的矩形
		g.fillRect(0, 0, width, height);
		//创建字体
		Font font = new Font("Times new Roman", Font.PLAIN, fontHeight);

		g.setColor(Color.black);
		g.setFont(font);
		Color juneFont = new Color(153, 204, 102);
		//随机产生130条干扰线
		g.setColor(juneFont);
		for (int j = 0; j < 130; j++) {
			int x = random.nextInt(width);
			int y = random.nextInt(height);
			int x1 = random.nextInt(16);
			int y1 = random.nextInt(16);

			g.drawLine(x, y, x + x1, y + y1);
		}
		//randomCode保存随机产生的验证码
		StringBuffer randomCode = new StringBuffer();
		//随机产生codeCount数字验证码
		for (int i = 0; i < codeCount; i++) {
			String strRand = String.valueOf(codeSequence[random.nextInt(36)]);

			//用随机产生的颜色将验证码绘制到图像中
			g.setColor(new Color(20 + random.nextInt(110), 20 + random
					.nextInt(110), 20 + random.nextInt(110)));

			//使用此图形上下文的当前文字和颜色绘制由指定string给定的文本
			g.drawString(strRand, (i + 1) * x - 4, codeY);
			randomCode.append(strRand);
		}
		HttpSession session = request.getSession();
		session.setAttribute("realcode", randomCode.toString());
		//禁止浏览器缓存
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		response.setContentType("image/gif");

		//将图像输出到Servlet输出流中
		ServletOutputStream sos = response.getOutputStream();
		ImageIO.write(Img, "gif", sos);
		sos.flush();
		sos.close();
	}
}
